"""
七牛云相关API路由
"""
import logging
from fastapi import APIRouter, Depends, Header, Request
from sqlalchemy.ext.asyncio import AsyncSession
from database.MysqlUtils import get_db
from database.RedisUtils import get_redis
from redis.asyncio.client import Redis
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import List
from utils import QiniuHelper
from service.qiniu_image_service import qiniu_image_service

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 创建路由
router = APIRouter()


@router.get("/qiniu/token")
async def get_qiniu_upload_token(
    request: Request,
    unionid: str = Header(None),
    db: AsyncSession = Depends(get_db),
    redis: Redis = Depends(get_redis),
    force_refresh: bool = False
):
    """
    获取七牛云上传Token
    
    参数:
    - force_refresh: 是否强制刷新token，默认为False
    
    返回:
    - token: 上传token
    - expires_in: token过期时间，单位秒
    """
    try:
        # 如果用户已登录，可以在这里添加权限验证
        if unionid:
            # 这里可以添加用户身份验证逻辑
            pass
            
        # 获取上传token
        token = QiniuHelper.get_upload_token(force_refresh=force_refresh)
        
        # 返回token和过期时间
        return JSONResponse(
            content={
                "code": 200,
                "msg": "获取上传Token成功",
                "data": {
                    "token": token,
                    "expires_in": 3600  # 默认1小时过期
                }
            }
        )
    except Exception as e:
        logger.error(f"获取七牛云上传Token失败: {str(e)}")
        return JSONResponse(
            status_code=500,
            content={
                "code": 500,
                "msg": f"获取七牛云上传Token失败: {str(e)}"
            }
        )

class ImageUploadTestRequest(BaseModel):
    image_urls: List[str]

@router.post("/qiniu/test-upload")
async def test_upload_images_from_urls(
    request_data: ImageUploadTestRequest,
    request: Request,
    unionid: str = Header(None)
):
    """
    测试从图片URL上传到七牛云的功能
    
    参数:
    - image_urls: 图片URL列表
    
    返回:
    - success: 是否成功
    - results: 上传结果列表
    - qiniu_urls: 七牛云图片URL列表
    """
    try:
        logger.info(f"开始测试上传图片到七牛云，URL数量: {len(request_data.image_urls)}")
        
        # 调用七牛云服务上传图片
        qiniu_urls = await qiniu_image_service.upload_images_from_urls(request_data.image_urls)
        
        # 构建详细结果
        results = []
        for i, original_url in enumerate(request_data.image_urls):
            if i < len(qiniu_urls):
                # 生成缩略图URL
                thumbnail_url = qiniu_image_service.generate_thumbnail_url(qiniu_urls[i])
                results.append({
                    "original_url": original_url,
                    "qiniu_url": qiniu_urls[i],
                    "thumbnail_url": thumbnail_url,
                    "success": True
                })
            else:
                results.append({
                    "original_url": original_url,
                    "qiniu_url": None,
                    "thumbnail_url": None,
                    "success": False
                })
        
        success_count = len(qiniu_urls)
        total_count = len(request_data.image_urls)
        
        logger.info(f"上传完成，成功: {success_count}/{total_count}")
        
        return JSONResponse(
            content={
                "code": 200,
                "msg": f"测试完成，成功上传 {success_count}/{total_count} 张图片",
                "data": {
                    "success": success_count == total_count,
                    "success_count": success_count,
                    "total_count": total_count,
                    "results": results,
                    "qiniu_urls": qiniu_urls
                }
            }
        )
        
    except Exception as e:
        logger.error(f"测试上传图片到七牛云失败: {str(e)}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "code": 500,
                "msg": f"测试上传失败: {str(e)}"
            }
        ) 